﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore2210A.Domain.Model;

namespace WorkflowCore2210A.Domain
{
    /// <summary>
    /// 仓储实现类
    /// </summary>
    /// <typeparam name="T">实体基类泛型</typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        /// <summary>
        /// 声明上下文字段
        /// </summary>
        private readonly WorkflowCoreContext db;
        /// <summary>
        /// 构造函数注入资源
        /// </summary>
        /// <param name="db">上下文</param>
        public BaseRepository(WorkflowCoreContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 泛型添加方法
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>受影响行数</returns>
        public int Add(T t)
        {
            try
            {
                db.Set<T>().Add(t);
                return db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 泛型查询方法
        /// </summary>
        /// <returns>满足条件的数据</returns>
        public IQueryable<T> GetAll()
        {
            try
            {
                return db.Set<T>().AsQueryable().AsNoTracking();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 泛型通过id查单条数据方法
        /// </summary>
        /// <param name="id">主键编号</param>
        /// <returns>单条数据</returns>
        public T GetModel(int id)
        {
            try
            {
                return db.Set<T>().Find(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 泛型修改方法
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>受影响行数</returns>
        public int Update(T t)
        {
            try
            {
                db.Set<T>().Update(t);
                return db.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
